﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace Coticula.Web.Models
{
    public class SpecificData
    {
        public int Id { get; set; }

        [Required, StringLength(32)]
        public string Name { get; set; }

        [Required, StringLength(32)]
        public string Value { get; set; }

        private const string LastServerConnectName = "LastServerConnect";
        public static DateTime LastServerConnect
        {
            get
            {
                CoticulaDbContext _db = new CoticulaDbContext();
                var lastServerConnect = (from t in _db.SpecificDatas where t.Name == LastServerConnectName select t).First();
                return DateTime.FromFileTimeUtc(long.Parse(lastServerConnect.Value)).ToLocalTime();
            }
            set
            {
                CoticulaDbContext _db = new CoticulaDbContext();
                var lastServerConnectList = (from t in _db.SpecificDatas where t.Name == LastServerConnectName select t);
                SpecificData lastServerConnect = null;
                if (lastServerConnectList.Count() == 0)
                {
                    lastServerConnect = new SpecificData();
                    lastServerConnect.Name = LastServerConnectName;
                    _db.SpecificDatas.Add(lastServerConnect);
                }
                else
                {
                    lastServerConnect = lastServerConnectList.First();
                }
                lastServerConnect.Value = value.ToFileTimeUtc().ToString();
                _db.SaveChanges();
            }
        }
    }
}